/* eslint-disable array-callback-return,no-undef,prefer-destructuring */
import React, { Component } from 'react';
import { Modal, message } from 'antd';
import * as commonConfig from '../../utils/config';
import * as commonBusiness from './commonBusiness'; /* 单据业务功能 */
import * as commonUtils from '../../utils/utils'; /* 通用方法 */
import * as commonServices from './../../services/services'; /*   服务类   */

const { confirm } = Modal;

export default (ChildComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      this.state = {};
      this.form = {};
      /*   表单对象   */
    }

    componentWillReceiveProps(nextProps) {
      const {
        formData, currentId, groupConfig, treeCheckedKeys, checkedNodesData, treeData, treeAllCheckKeys, treeAllNodes,
      } = nextProps;
      let { bReceived } = nextProps;
      const sId = currentId !== undefined ? currentId : '';

      if (commonUtils.isEmptyObject(groupConfig) && bReceived === undefined) {
        const masterConfig = formData.filter(item => !item.bGrd)[0];
        bReceived = false;
        const group = this.imitateTableColumnConfig('group', [this.imitateTableColumn('组权限', 'sName', 'sId')]);
        const user = this.imitateTableColumnConfig('user', [this.imitateTableColumn('用户账号', 'sUserName', 'sId')]);

        const userGroup = this.imitateTableColumnConfig('userGroup', [this.imitateTableColumn('组成员', 'sUserName', 'sUsersId')]);
        const groupUser = this.imitateTableColumnConfig('groupUser', [this.imitateTableColumn('所属分组', 'sGroupName', 'sGroupsId')]);

        const checkedNodes = this.imitateTableColumnConfig('checkedNodes', [this.imitateTableColumn('名称', 'sShowName', 'sId')]);

        const tree = this.imitateTableColumnConfig('tree', [this.imitateTableColumn('名称', 'sShowName', 'key')]);

        this.handleGetChangeData({ name: 'tree' }, 'SysjurisdictionTree');
        this.handleGetChangeData({ name: 'group' }, 'GroupData');
        this.handleGetChangeData({ name: 'user' }, 'UserData');

        this.props.onSaveState({
          masterConfig,
          sId,
          bReceived,
          treeKeyName: 'key',
          showLine: false,
          ...tree,
          ...group,
          ...user,
          ...userGroup,
          ...groupUser,
          ...checkedNodes,
        });
      }

      if (commonUtils.isEmptyArr(treeAllCheckKeys) && (commonUtils.isEmptyObject(treeAllNodes) || treeAllNodes.size === 0) && commonUtils.isNotEmptyArr(treeData)) {
        const allInitArr = [];
        const allInitMap = new Map();
        this.handleAllCheckKeys(allInitArr, allInitMap, treeData);
        this.props.onSaveState({ treeAllCheckKeys: allInitArr, treeAllNodes: allInitMap });
      }
      if (commonUtils.isNotEmptyArr(treeCheckedKeys) && commonUtils.isNotEmptyObject(treeAllNodes) && treeAllNodes.size > 0 && commonUtils.isEmptyArr(checkedNodesData)) {
        this.handleCheckedForFunction('tree', treeCheckedKeys);
        this.props.onSaveState({ pageLoading: false });
      }
    }


    shouldComponentUpdate(nextProps, nextState) {
      let flag = true;
      /* 追加弹出框数值回填放行判断ppopupPane */
      if (nextProps.sTabId === nextProps.app.currentPane.key || ((nextProps.app.ppopupPane !== undefined
          && nextProps.app.ppopupPane.mainConfig !== undefined)
        ? nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key : false)) {
        if (nextState.disabled !== this.state.disabled) {
          return true;
        }
        flag = true;
      } else {
        flag = false;
      }
      return flag;
    }

    componentWillUpdate(nextProps) {
      const { masterData, sModelsType, elemachineData } = nextProps;
      if (sModelsType === 'element/teamInfo' && masterData !== undefined) {
        if (commonUtils.isNotEmptyObject(elemachineData)) {
          elemachineData.forEach((row, index) => {
            if (row.sMachineId === masterData.sMachineId) {
              elemachineData[index].bDefault = true;
            } else {
              elemachineData[index].bDefault = false;
            }
          });
        }
      }
    }


    /**   表单回带   */
    handleForm = (form) => {
      this.form = form;
    };
    /** 主表控件是否全部显示 */
    handleToggle = () => {
      const { expand } = this.props;
      this.props.onSaveState({ expand: !expand });
    };

    handleValidateSave = async () => {
      const {
        token, sModelsId, sJurisdictionClassifyId, sUserId, treeSaveParams,
      } = this.props;
      const value = {};
      if ((commonUtils.isEmptyArr(sJurisdictionClassifyId) || commonUtils.isEmptyArr(sUserId)) && commonUtils.isEmptyArr(treeSaveParams)) {
        message.warn('组员，所属或权限组不能为空!');
        return;
      }
      if (commonUtils.isNotEmptyArr(sJurisdictionClassifyId) && commonUtils.isEmptyArr(sUserId)) {
        value.sJurisdictionClassifyId = sJurisdictionClassifyId[0];
      } else if (commonUtils.isNotEmptyArr(sUserId) && commonUtils.isEmptyArr(sJurisdictionClassifyId)) {
        value.sUserId = sUserId[0];
      } else {
        message.warn('组或者组员不能为空!');
        return;
      }
      value.data = treeSaveParams;

      const dataUrl = `${commonConfig.server_host}/sysjurisdiction/addSysjurisdiction?sModelsId=${sModelsId}`;
      const dataReturn = (await commonServices.postValueService(token, value, dataUrl)).data;
      /*   成功的话返回数据   */
      if (dataReturn.code === 1) { /*   成功   */
        message.success(dataReturn.msg);
        return dataReturn;
      } else { /*   失败   */
        message.error(dataReturn.msg);
        return false;
      }
    }

    /**   点击修改按钮操作   */
    handleEdit = () => {
      this.props.onSaveState({ enabled: true });
    }
    handleCancel = (obj) => {
      const { groupUserData } = this.props;
      const onGetChangeData = this.handleGetChangeData;
      const onSaveStateOk = this.props.onSaveState;
      confirm({
        title: obj.title,
        onOk() {
          const sId = groupUserData.length > 0 ? groupUserData[0].sId : '';
          onSaveStateOk({ enabled: false });
          onGetChangeData({ name: 'authority', sId }, 'GroupAuthority');
        },
        onCancel() {
        },
      });
    }

    handleGetSisformulaData = (masterConfig) => {
      this.handleGetSlaveData('One', null, masterConfig);
    }

    handleGetSlaveData = (getType, sName, currConfig) => {
      const { currentId } = this.props;
      /* 当前页签数据 */
      const sId = currentId !== undefined ? currentId : '';
      if (getType === 'One') {
        this.props.handleGetDataOne({
          name: 'master', configData: currConfig, condition: { sId, pageSize: '', pageNum: '' },
        });
      }
      if (getType === 'Set') {
        this.props.handleGetDataSet({
          name: sName, configData: currConfig, condition: { sSqlCondition: { sParentId: sId } },
        });
      }
    }
    /*  获取分组列表
    yw_权限分配
    获取分组列表
    获取人员列表
    qx_获取权限树
    qx_根据组sId获取已选择权限
    qx_根据人sId获取已选择权限
    qx_根据组sId获取组人员
    根据人员sId获取所属分组
    保存组已选权限
    * */
    handleGetChangeData = async (params, urlKey) => {
      const { app, sModelsId } = this.props;
      const { token } = app;
      const { name, sId, treeComponentName } = params; // name,
      let dataUrl = '';
      if (urlKey === 'SysjurisdictionTree') { // 树结构
        dataUrl = `${commonConfig.server_host}sysjurisdiction/getSysjurisdictionTree?sModelsId=${sModelsId}`;
      } else if (urlKey === 'GroupData') { // 组
        dataUrl = `${commonConfig.server_host}sysjurisdiction/getGroupData?sModelsId=${sModelsId}`;
      } else if (urlKey === 'UserData') { // 用户
        dataUrl = `${commonConfig.server_host}sysjurisdiction/getUserData?sModelsId=${sModelsId}`;
      } else if (urlKey === 'UserGroupId') { // 组成员
        dataUrl = `${commonConfig.server_host}sysjurisdiction/getsUserGroupId/${sId}?sModelsId=${sModelsId}`;
      } else if (urlKey === 'GroupUserId') { // 用户所属组
        dataUrl = `${commonConfig.server_host}sysjurisdiction/getGroupUserId/${sId}?sModelsId=${sModelsId}`;
      } else if (urlKey === 'GroupAuthority') { // 组权限
        dataUrl = `${commonConfig.server_host}sysjurisdiction/getHaveAuthorityGroupId/${sId}?sModelsId=${sModelsId}`;
      } else if (urlKey === 'UserAuthority') { // 用户所有权限查询 :用户权限，组权限
        dataUrl = `${commonConfig.server_host}sysjurisdiction/getHaveAuthorityUserId/${sId}?sModelsId=${sModelsId}`;
      }

      const dataReturn = (await commonServices.getService(token, dataUrl)).data;
      if (dataReturn.code === 1) {
        const returnData = dataReturn.dataset.rows;

        if (urlKey === 'SysjurisdictionTree') { // 树结构
          const allInitArr = [];
          const allInitMap = new Map();
          this.handleAllCheckKeys(allInitArr, allInitMap, returnData);
          this.props.onSaveState({ [`${name}Data`]: returnData, treeAllCheckKeys: allInitArr, treeAllNodes: allInitMap });
        } else if (urlKey === 'GroupData') { // 获取组后默认查询组权限，以及组成员
          this.props.onSaveState({ [`${name}Data`]: returnData });
          this.handleTableSelectRowChange('group', returnData[0].sId);
        } else if (urlKey === 'UserData') { // 获取成员后默认 成员自己的权限，以及成员所属组
          const item = returnData[0];
          this.props.onSaveState({ [`${name}Data`]: returnData });
          this.handleGetChangeData({ name: 'groupUser', sId: item.sId }, 'GroupUserId');
        } else if (urlKey === 'GroupAuthority') {
          let groupAuth = '';
          let groupAuthData = [];
          if (commonUtils.isNotEmptyArr(returnData)) {
            if (commonUtils.isNotEmptyObject(returnData[0])) {
              groupAuth = commonUtils.isNotEmptyObject(returnData[0]) ? returnData[0].sKeys : [];
              groupAuthData = commonUtils.isNotEmptyObject(groupAuth) ? groupAuth.split(',') : [];
            }
          }
          this.props.onSaveState({
            [`${treeComponentName}CheckedKeys`]: groupAuthData, [`${name}Data`]: returnData, userAuth: undefined, sJurisdictionClassifyId: sId, sUserId: undefined,
          });
        } else if (urlKey === 'UserAuthority') {
          let gAuth = '';
          let groupAuthData = [];
          let uAuth = '';
          let userAuthData = [];
          if (commonUtils.isNotEmptyArr(returnData)) {
            if (commonUtils.isNotEmptyObject(returnData[0])) {
              const { groupAuth, userAuth } = returnData[0];
              if (commonUtils.isNotEmptyObject(groupAuth)) {
                gAuth = groupAuth.sKeys;
                groupAuthData = gAuth.split(',');
              }

              if (commonUtils.isNotEmptyObject(userAuth)) {
                uAuth = userAuth.sKeys;
                userAuthData = uAuth.split(',');
              }
            }
          }
          // console.log([`${treeComponentName}CheckedKeys`], groupAuthData.concat(userAuthData));
          this.props.onSaveState({
            [`${treeComponentName}CheckedKeys`]: groupAuthData.concat(userAuthData), [`${name}Data`]: returnData, disabledCheckedKeys: groupAuthData, userAuthData, sJurisdictionClassifyId: undefined, sUserId: sId,
          });
        } else {
          this.props.onSaveState({ [`${name}Data`]: returnData });
        }
      } else {
        message.error(dataReturn.msg);
      }
    }

    // 模拟 列
    imitateTableColumn = (title, dataIndex, key) => {
      return { title, dataIndex, key };
    }
    // 模拟config的 gdsconfigformslave 配置
    imitateTableConfig = (title, dataIndex) => {
      return {
        bCanInput: false,
        bFilter: false,
        bFind: false,
        bFirstEmpty: false,
        bIsOther: false,
        bNewRecord: false,
        bNotEmpty: false,
        bNotRepeat: false,
        bReadonly: true,
        bSum: false,
        bTree: false,
        bVisible: true,
        iColValue: 1,
        iFitWidth: 120,
        sBrandsId: '1111111111',
        sChinese: title,
        sChineseDropDown: '',
        sControlName: 'BtnLast',
        sId: commonUtils.createSid(),
        sParentId: '11811781131121915102156308120',
        sSubsidiaryId: '1111111111',
        showName: title,
        sName: dataIndex,
      };
    }
    // 根据模拟列，模拟列配置
    imitateTableColumnConfig = (name, columns) => {
      const gdsconfigformslave = [];
      columns.forEach((itmes) => {
        gdsconfigformslave.push(this.imitateTableConfig(itmes.title, itmes.dataIndex));
      });
      const config = { bGrd: true, gdsconfigformslave };
      return { [`${name}Column`]: columns, [`${name}Config`]: config };
    }
    /**   处理选择行发生改变   */
    handleTableSelectRowChange = (name, selectedRowKeys) => {
      // console.log('handleTableSelectRowChange: ', name, selectedRowKeys);
      if (name === 'group') {
        this.handleGetChangeData({ name: 'userGroup', sId: selectedRowKeys }, 'UserGroupId');
        this.handleGetChangeData({ name: 'master', sId: selectedRowKeys, treeComponentName: 'tree' }, 'GroupAuthority');
      } else if (name === 'user') {
        this.handleGetChangeData({ name: 'groupUser', sId: selectedRowKeys }, 'GroupUserId');
        this.handleGetChangeData({ name: 'master', sId: selectedRowKeys, treeComponentName: 'tree' }, 'UserAuthority');
      } else if (name === 'userGroup') {
        this.handleGetChangeData({ name: 'master', sId: selectedRowKeys, treeComponentName: 'tree' }, 'UserAuthority');
      } else if (name === 'groupUser') {
        this.handleGetChangeData({ name: 'master', sId: selectedRowKeys, treeComponentName: 'tree' }, 'GroupAuthority');
      }
    }

    handleCheckBoxCheck = (componentName, checkedKeys) => {
      this.handleCheckedForFunction(componentName, checkedKeys);
    }

    /* 选择权限同时处理保存的数据以及将要展现的已选择权限  */
    handleCheckedForFunction = (componentName, checkedKeys) => {
      const {
        treeAllNodes, [`${componentName}KeyName`]: skeyName,
      } = this.props;
      const data = [];
      const checkedData = [];
      if (commonUtils.isNotEmptyArr(checkedKeys) && checkedKeys[0] !== null && commonUtils.isNotEmptyObject(treeAllNodes) && treeAllNodes.size > 0) {
        const newCheckedKeys = [];
        checkedKeys.forEach((key, i) => {
          if (checkedKeys.indexOf(key) === i) {
            newCheckedKeys.push(key);
          }
        });
        newCheckedKeys.forEach((key) => {
          const nodes = treeAllNodes.get(key);
          if (commonUtils.isNotEmptyObject(nodes)) {
            data.push({ sKey: nodes[`${skeyName}`], sAction: nodes.sName });
            checkedData.push({ sId: nodes.sId, sShowName: nodes.sShowName });
          }
        });
        this.props.onSaveState({
          [`${componentName}CheckedKeys`]: newCheckedKeys,
          treeSaveParams: data,
          checkedNodesData: checkedData,
        });
      }
    }

    handleAllCheckKeys = (arrObj, mapObj, returnData) => {
      const { treeKeyName } = this.props;
      returnData.forEach((item) => {
        if (item.children.length > 0) {
          arrObj.push(item[`${treeKeyName}`]);
          mapObj.set(item[`${treeKeyName}`], item);
          this.handleAllCheckKeys(arrObj, mapObj, item.children);
        } else {
          arrObj.push(item[`${treeKeyName}`]);
          mapObj.set(item[`${treeKeyName}`], item);
        }
      });
    }
    handleRefresh = () => {
      this.handleGetChangeData({ name: 'tree' }, 'SysjurisdictionTree');
      this.handleGetChangeData({ name: 'group' }, 'GroupData');
      this.handleGetChangeData({ name: 'user' }, 'UserData');
      this.props.onSaveState({
        treeAllCheckKeys: undefined,
        treeAllNodes: undefined,
      });
    }
    render() {
      const { masterData } = this.props;
      const imgSrc = commonBusiness.handleAddIcon(masterData);
      return (
        <ChildComponent
          {...this.props}
          {...this.state}
          onReturnForm={this.handleForm}
          onSubmit={this.handleValidateSave}
          onEdit={this.handleEdit}
          onTableSelectRowChange={this.handleTableSelectRowChange}
          onCancel={this.handleCancel}
          imgSrc={imgSrc}
          onToggle={this.handleToggle}
          onTreeCheck={this.handleCheckBoxCheck}
          onRefresh={this.handleRefresh}
          /*
          onAdd={this.handleAdd}
          onDel={this.handleDel}
          onReturnForm={this.handleForm}
          onChangeInvalid={this.handleInvalid}

          */
        />
      );
    }
  };
};
